package cn.tedu.csmall.passport.ex.handler;

import cn.tedu.csmall.passport.ex.ServiceException;
import cn.tedu.csmall.passport.web.JsonResult;
import cn.tedu.csmall.passport.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.nio.file.AccessDeniedException;

/**
 * 全局异常处理器
 *
 * @author wys
 * @version 0.0.1
 *
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler() {
        log.debug("创建全局异常处理器对象: GlobalExceptionHandler");
    }


    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException e){
        log.debug("捕获到ServiceException: {}", e.getMessage());
        return JsonResult.fail(e.getServiceCode(), e.getMessage());
    }

    @ExceptionHandler ({InternalAuthenticationServiceException.class,// AuthenticationServiceException >> AuthenticationException >> RuntimeException
            BadCredentialsException.class // AuthenticationException
    })
    public JsonResult handleAuthenticationException(AuthenticationException e){
        log.debug("捕获到AuthenticationException");
        log.debug("异常类型: {}",e.getClass().getName());
        log.debug("异常信息: {}", e.getMessage());
        String message = "登录失败, 用户名或密码错!";
        return JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED, message);
    }


    @ExceptionHandler
    public JsonResult handleDisabledException(DisabledException e){
        log.debug("捕获到DisabledExeption: {}",e.getMessage());
        String message = "登录失败, 此管理员账号已经被禁用!";
        return JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED_DISABLED, message);
    }


    @ExceptionHandler
    public JsonResult handleAccessDeniedException(AccessDeniedException e){
        log.debug("捕获到AccessDeniedExeption: {}",e.getMessage());
        String message = "请求失败, 当前登录的账号不具备此操作权限!";
        return JsonResult.fail(ServiceCode.ERR_FORBIDDEN, message);
    }


    @ExceptionHandler
    public String handleThrowable(Throwable e){
        log.debug("捕获到Throwable: {}",e.getMessage());
        e.printStackTrace(); //强烈建议
        String message = "程序运行时出现未知错误, 请联系系统管理员!";
        return message;

    }
}
